package lumis.portal.presentation.tag.page;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.manager.ManagerFactoryInternal;
import lumis.portal.page.IPageManager;
import lumis.portal.page.PageConfig;
import lumis.portal.page.webresource.PageWebResourceData;
import lumis.portal.presentation.PageDocType;
import lumis.portal.presentation.core.HTMLFragmentComponent;
import lumis.portal.presentation.core.LayoutFilePage;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.util.XmlUtil;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.util.string.AppendingStringBuffer;

/**
 * Injects the meta tags components in the page.
 * @version $Revision: 13093 $ $Date: 2011-05-28 18:40:18 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class PageMetaTagsComponent extends HTMLFragmentComponent 
{
	/**
	 * Comment for <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor for the class.
	 * @param id component identifier
	 * @since 6.0.0
	 */
	public PageMetaTagsComponent(String id, boolean autoRenderBodyOnly) 
	{
		super(id, autoRenderBodyOnly);
	}

	@Override
	protected CharSequence getHTMLFragment(MarkupStream markupStream, ComponentTag openTag) 
	{
		try
		{
			AppendingStringBuffer pageMetaTags = new AppendingStringBuffer(1024);
			
			LayoutFilePage page = ((LayoutFilePage)getPage());
			SessionConfig sessionConfig = SessionConfig.getCurrentSessionConfig();
			PageConfig pageConfig = page.getPageWebResource().getPage();
			PageWebResourceData pageWebResourceData =page.getPageWebResource().getPageWebResourceData();
			
			PageDocType pageDocType = page.getPageDocType();
			pageMetaTags.append(pageDocType.formatW3CClosedTag("meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\""));
			
			if (pageWebResourceData != null)
			{
				Map<String, String> metaTagsMap = new HashMap<String, String>(pageWebResourceData.getMetaTags());
				
				String description = metaTagsMap.containsKey("description")?metaTagsMap.remove("description"):pageWebResourceData.getDescription();
				if (description != null && description.length() > 0)
				{
					pageMetaTags.append(pageDocType.formatW3CClosedTag("meta name=\"description\" content=\"" + XmlUtil.encodeXml(description) + "\""));
				}

				if (metaTagsMap.containsKey("keywords"))
				{
					String keywordsValue = metaTagsMap.remove("keywords");
					if ((keywordsValue != null) && (!"".equals(keywordsValue)))
					{
						pageMetaTags.append(pageDocType.formatW3CClosedTag("meta name=\"keywords\" content=\"" + keywordsValue + "\""));
					}
				}
				else
				{
					List<String> keywords = pageWebResourceData.getKeywords();
					if (keywords != null && keywords.size() > 0)
					{
						String strKeywords = "meta name=\"keywords\" content=\"";
						for (Iterator<String> itKeywords = keywords.iterator(); itKeywords.hasNext();)
						{
							strKeywords += XmlUtil.encodeXml(itKeywords.next());
							if (itKeywords.hasNext())
								strKeywords += ",";
						}
						strKeywords += "\"";
						pageMetaTags.append(pageDocType.formatW3CClosedTag(strKeywords));
					}
				}
				
				for (Map.Entry<String, String> metaTagEntry: metaTagsMap.entrySet())
				{
					String metaTagContent = metaTagEntry.getValue();
					if ((metaTagContent != null) && (!"".equals(metaTagContent)))
					{
						pageMetaTags.append(pageDocType.formatW3CClosedTag("meta name=\"" + XmlUtil.encodeXml(metaTagEntry.getKey()) + "\" content=\"" + XmlUtil.encodeXml(metaTagContent) + "\""));
					}
				}
			}
			
			IPageManager pageManager = ManagerFactory.getPageManager();
			List<String> metaTagIds = pageManager.getMetaTagIdsRecursively(sessionConfig, pageConfig, PortalTransactionFactory.getCurrentTransaction());

			for (String metaTagId : metaTagIds)
			{
				String metaTagContent = ManagerFactoryInternal.getMetaTagManager().get(sessionConfig, metaTagId, PortalTransactionFactory.getCurrentTransaction()).getContent();
				pageMetaTags.append(metaTagContent);
			}

			pageMetaTags.append(pageDocType.formatW3CClosedTag(
					"meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\""));
			
			pageMetaTags.append(pageDocType.formatW3CClosedTag(
					"meta http-equiv=\"Content-Style-Type\" content=\"text/css\""));
			
			return pageMetaTags;
		}
		catch (PortalException e)
		{
			throw new RuntimeException(e);
		}

	}
}
